<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace think\template\taglib\api;

use think\Db;

/**
 * 秒杀
 */
class TagSharp extends Base
{
    //初始化
    protected function _initialize()
    {
        parent::_initialize();
    }

    //获取天活动场次(包括当天所有小时场)
    public function apiSharpActive($param)
    {
        $avtive_id = !empty($param['activeid']) ? intval($param['activeid']) : 0;

        $return = [];

        if (empty($avtive_id)) {
            //获取当时时间的整点时间戳
            $time = strtotime(date('Y-m-d'));
            $hour = date('H');
            $where['a.status'] = 1;
            $where['a.is_del'] = 0;
            $where['b.status'] = 1;
            $where['b.active_time'] = ['>=', $hour];
            //获取今天秒杀
            $active = Db::name('sharp_active')
                ->alias('a')
                ->where($where)
                ->join('sharp_active_time b', 'a.active_id = b.active_id')
                ->where('a.active_date', $time)
                ->find();
            if (empty($active)) {
                //今日秒杀结束或者没有获取后面天的秒杀
                $active = Db::name('sharp_active')
                    ->where('status', 1)
                    ->where('is_del', 0)
                    ->where('active_date', '>', $time)
                    ->find();
            }
        } else {
            $active = Db::name('sharp_active')
                ->where('status', 1)
                ->where('is_del', 0)
                ->where('avtive_id', $avtive_id)
                ->find();
        }

        if (!empty($active)) {
            //获取当天所有秒杀场次
            $active_time = Db::name('sharp_active_time')
                ->where('status', 1)
                ->where('active_id', $active['active_id'])
                ->order('active_time asc')
                ->select();
            //今日秒杀
            if ($active['active_date'] == $time) {
                foreach ($active_time as $k => $v) {
                    if ($v['active_time'] >= $hour) {
                        if ($v['active_time'] == $hour) {
                            $return['active']['status'] = 10;
                        } else {
                            $return['active']['status'] = 20;
                        }
                        $return['active']['active_time_id'] = $v['active_time_id'];
                        $start_time = $v['active_timestamp'];
                        break;
                    }
                }
            } else {
                //非今日秒杀
                $return['active']['status'] = 30;
                $return['active']['active_time_id'] = $active[0]['active_time_id'];
                $start_time = $active[0]['active_timestamp'];
            }
            foreach ($active_time as $k => $v) {
                $active_time[$k]['active_time'] = $this->time_format($v['active_timestamp']);
            }
            $return['active_time_list'] = $active_time;

            $end_time = $start_time + 3600; //2020-15-2-15 15:00
            $end_time_arr = $this->time_format($end_time);
            $start_time_arr = $this->time_format($start_time);

            $return['active']['active_status'] = 'today';
            if (10 == $return['active']['status']) {
                $count_down_time = $start_time_arr;
            } else if (20 == $return['active']['status']) {
                $count_down_time = $start_time;
            } else if (30 == $return['active']['status']) {
                $count_down_time = $start_time;
                $return['active']['active_status'] = 'next';//不是当天场次,是过后某天的场次
            }
            $return['active']['active_time'] = date('H:i', $start_time);
            $return['active']['count_down_time'] = $count_down_time;
            $return['active']['end_time'] = $end_time_arr;
            $return['active']['start_time'] = $start_time_arr;
            $return['active']['active_id'] = $active['active_id'];
            $return['goodsList'] = $this->getSharpTimeGoodsList($return['active']['active_time_id']);
        }
        return $return;
    }

    //获取当场活动  小时场
    public function getSharpTime($param)
    {
        $active_time_id = !empty($param['tid']) ? intval($param['tid']) : 0;

        if (empty($active_time_id)) {
            //获取当时时间的整点时间戳
            $time = getTime();
            $time = date('Y-m-d H:00:00', $time);
            $time = strtotime($time);
            $where['status'] = 1;
            $where['active_timestamp'] = $time;
            //获取今天秒杀
            $active_time = Db::name('sharp_active_time')
                ->where($where)
                ->find();
            if (empty($active_time)) {
                //今日秒杀结束或者没有获取后面天的秒杀
                $active_time = Db::name('sharp_active_time')
                    ->where('status', 1)
                    ->where('active_timestamp', '>', $time)
                    ->order('active_timestamp asc')
                    ->find();
            }
        } else {
            $active_time = Db::name('sharp_active_time')
                ->where('status', 1)
                ->where('active_time_id', $active_time_id)
                ->find();
        }

        if (!empty($active_time)) {
            //本场结束时间
            $end_time = $active_time['active_timestamp'] + 3600; //2020-15-2-15 15:00
            $end_time_arr = $this->time_format($end_time);
            $start_time_arr = $this->time_format($active_time['active_timestamp']);
//            $end_time_date = date('Y-m-d H:i',$end_time); //2020-15-2-15 16:00
//            $start_time_date = date('Y-m-d H:i',$active_time['active_timestamp']); //2020-15-2-15 16:00

            if ($end_time < getTime()) {
                //已经结束
                $active_time['status'] = 30;
                $count_down_time = $end_time_arr;
            } elseif (getTime() < $active_time['active_timestamp']) {
                //未开始
                $active_time['status'] = 20;
                $count_down_time = $start_time_arr;
            } elseif (getTime() >= $active_time['active_timestamp'] && getTime() < $end_time) {
                //进行中
                $active_time['status'] = 10;
                $count_down_time = $end_time_arr;
            }

            $active_time['count_down_time'] = $count_down_time;
            $active_time['end_time_arr'] = $end_time_arr;
            $active_time['start_time_arr'] = $start_time_arr;

            $active_time['goodsList'] = $this->getSharpTimeGoods($param, $active_time['active_time_id']);
        }
        return $active_time;
    }

    /**
     * 限时秒杀：获取秒杀商品列表  不分页
     */
    public function getSharpTimeGoods($param, $tid)
    {
        $pagesize = !empty($param['pagesize']) ? intval($param['pagesize']) : 6;
        $where['a.active_time_id'] = $tid;
        $where['b.status'] = 1;
        $where['b.is_del'] = 0;
        $data = Db::name('sharp_active_goods')
            ->alias('a')
            ->field('c.*,b.litpic,b.title,a.*,b.users_price')
            ->join('archives b', 'a.aid = b.aid','left')
            ->join('sharp_goods c', 'a.sharp_goods_id = c.sharp_goods_id','left')
            ->where($where)
            ->limit($pagesize)
            ->getAllWithIndex('aid');
        if (!empty($data)) {
            $aids = [];
            foreach ($data as $k => $v) {
                $data[$k]['litpic'] = get_default_pic($v['litpic'], true);
                if (1 == $v['is_sku']) {
                    $aids[] = $v['aid'];
                }
            }
            //多规格
            if (!empty($aids)) {
                $sku = Db::name('product_spec_value')
                    ->field('*,min(seckill_price) as seckill_price')
                    ->where('aid', 'in', $aids)
                    ->group('aid')
                    ->getAllWithIndex('aid');
            }
            //sales_actual //
            foreach ($data as $k => $v) {
                if (1 == $v['is_sku'] && !empty($sku[$v['aid']])) {
                    $v['seckill_price'] = $sku[$v['aid']]['seckill_price'];
                }
                $v['progress'] = 0;
                if (0 < $v['sales_actual']) {
                    $count_stock = $v['sales_actual'] + $v['seckill_stock'] + $v['virtual_sales'];
                    $v['progress'] = intval(($v['sales_actual'] + $v['virtual_sales']) / $count_stock * 100);
                } else {
                    if (0 < $v['virtual_sales']) {
                        $v['progress'] = intval($v['virtual_sales'] / ($v['virtual_sales'] + $v['seckill_stock']) * 100);;
                    }
                }
                if (0 < $v['virtual_sales']) {
                    $v['sales_actual'] = $v['sales_actual'] + $v['virtual_sales'];
                }
                $v['seckill_price_arr'] = explode('.', $v['seckill_price']);
                $data[$k] = $v;
            }
        }
        return $data;
    }

    /**
     * 限时秒杀：获取秒杀商品列表  分页
     */
    public function getSharpTimeGoodsList($tid, $page = 1, $pagesize = 10)
    {
        $paginate = array(
            'page' => $page,
        );

        $where['a.active_time_id'] = $tid;
        $where['b.status'] = 1;
        $where['b.is_del'] = 0;

        $pages = Db::name('sharp_active_goods')
            ->alias('a')
            ->field('c.*,b.litpic,b.title,a.*,b.users_price')
            ->join('archives b', 'a.aid = b.aid','left')
            ->join('sharp_goods c', 'a.sharp_goods_id = c.sharp_goods_id','left')
            ->where('a.active_time_id', $tid)
            ->paginate($pagesize, false, $paginate);

        $data = $pages->toArray();

        if (!empty($data['data'])) {
            $aids = [];
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['litpic'] = get_default_pic($v['litpic'], true);
                if (1 == $v['is_sku']) {
                    $aids[] = $v['aid'];
                }
            }
            //多规格
            if (!empty($aids)) {
                $sku = Db::name('product_spec_value')
                    ->field('*,min(seckill_price) as seckill_price')
                    ->where('aid', 'in', $aids)
                    ->group('aid')
                    ->getAllWithIndex('aid');
            }
            //sales_actual //
            foreach ($data['data'] as $k => $v) {
                if (1 == $v['is_sku'] && !empty($sku[$v['aid']])) {
                    $v['seckill_price'] = $sku[$v['aid']]['seckill_price'];
                }
                $v['progress'] = 0;
                if (0 < $v['sales_actual']) {
                    $count_stock = $v['sales_actual'] + $v['seckill_stock'] + $v['virtual_sales'];
                    $v['progress'] = intval(($v['sales_actual'] + $v['virtual_sales']) / $count_stock * 100);
                } else {
                    if (0 < $v['virtual_sales']) {
                        $v['progress'] = intval($v['virtual_sales'] / ($v['virtual_sales'] + $v['seckill_stock']) * 100);;
                    }
                }
                if (0 < $v['virtual_sales']) {
                    $v['sales_actual'] = $v['sales_actual'] + $v['virtual_sales'];
                }
                $v['seckill_price_arr'] = explode('.', $v['seckill_price']);
                $data['data'][$k] = $v;
            }
        }
        return $data;
    }

    //获取秒杀商品详情
    public function getSharpGoodsView($id = 0,$users = [])
    {
        $id = intval($id);
        $args = [$id,$users];
        $cacheKey = 'api-' . md5(__CLASS__ . __FUNCTION__ . json_encode($args));
        $detail = cache($cacheKey);
        if (true || empty($detail)) {
            $detail = [];
            $field = 'a.aid,a.typeid,a.channel,a.title,a.subtitle,a.litpic,a.video_paths,a.video_times,a.author,a.click,a.arcrank,a.seo_title,a.seo_keywords,
            a.seo_description,a.users_price,a.market_price,a.users_free,a.old_price,a.stock_show,a.stock_count,a.prom_type,a.arc_level_id,a.downcount,a.add_time,
            a.attrlist_id,a.freight_fee_set,a.freight_fee_tpl,a.sales_show,a.goods_unit,a.goods_spec,b.typename,c.*';
            $detail = Db::name('sharp_active_goods')
                ->alias('c')
                ->field($field)
                ->join('archives a', 'a.aid = c.aid', 'left')
                ->join('arctype b', 'a.typeid = b.id', 'left')
                ->where([
                    'c.id' => $id,
                    'a.status' => 1,
                    'a.is_del' => 0,
                ])
                ->find();

            if (!empty($detail)) {
                $aid = $detail['aid'];
                //秒杀场次信息 开始
                $active_time = Db::name('sharp_active_time')->where('active_time_id',$detail['active_time_id'])->find();
                //本场结束时间
                $end_time = $active_time['active_timestamp'] + 3600; //2020-15-2-15 15:00
                $end_time_arr = $this->time_format($end_time);
                $start_time_arr = $this->time_format($active_time['active_timestamp']);
                if ($end_time < getTime()) {
                    //已经结束
                    $active_time['status'] = 30;
                    $count_down_time = $end_time_arr;
                } elseif (getTime() < $active_time['active_timestamp']) {
                    //未开始
                    $active_time['status'] = 20;
                    $count_down_time = $start_time_arr;
                } elseif (getTime() >= $active_time['active_timestamp'] && getTime() < $end_time) {
                    //进行中
                    $active_time['status'] = 10;
                    $count_down_time = $end_time_arr;
                }

                $active_time['count_down_time'] = $count_down_time;
                $active_time['end_time_arr'] = $end_time_arr;
                $active_time['start_time_arr'] = $start_time_arr;
                $detail['active_time'] = $active_time;
                //秒杀场次信息 结束
                $detail['active_goods'] = Db::name('sharp_goods')->where('aid',$aid)->find();

                // 价格拆分
                if (!empty($detail['users_price'])) $detail['users_price_arr'] = explode('.', $detail['users_price']);
                // 视频处理
                if (!empty($detail['video_paths'])) {
                    $detail['video_paths'] = $this->get_default_pic($detail['video_paths'], true);
                }
                if (!empty($detail['video_times'])) {
                    if (intval($detail['video_times']) < 60) {
                        $detail['video_times'] = '00′' . $detail['video_times'] . '″';
                    }
                }
                // 商品运费处理
                if (!empty($detail['freight_fee_set']) && 2 === intval($detail['freight_fee_set']) && !empty($detail['freight_fee_tpl'])) {
                    $where = [
                        'template_id' => intval($detail['freight_fee_tpl'])
                    ];
                    $freightTemplate = Db::name('shop_freight_template')->field('template_data, special_set, special_ids')->where($where)->find();
                    $templateData = !empty($freightTemplate['template_data']) ? unserialize($freightTemplate['template_data']) : [];
                    $detail['freight_fee'] = !empty($templateData[0]['freight_fee']) ? sprintf("%.2f", floatval($templateData[0]['freight_fee'])) : 0;

                } else {
                    $detail['freight_fee'] = '包邮';
                }
                // 商品标签处理
                $where = [
                    'a.aid' => intval($detail['aid'])
                ];
                $goodsLabel = Db::name('product_label')->alias('a')
                    ->field('b.*')
                    ->where($where)
                    ->join('__LABEL_TYPES__ b', 'a.types_id = b.types_id', 'LEFT')
                    ->select();
                $goodsLabel = group_same_key($goodsLabel, 'types_value');
                $marketingLabel = !empty($goodsLabel[1][0]['types_names']) ? $goodsLabel[1][0]['types_names'] : '';
                $detail['marketingLabel'] = $marketingLabel;
                $serviceLabel = !empty($goodsLabel[2]) ? $goodsLabel[2] : [];
                $detail['serviceLabel'] = $serviceLabel;
                // 模型标题处理
                $channeltype_row = \think\Cache::get('extra_global_channeltype');
                $channeltypeInfo = !empty($channeltype_row[$detail['channel']]) ? $channeltype_row[$detail['channel']] : [];
                $detail['channel_ntitle'] = !empty($channeltypeInfo['ntitle']) ? $channeltypeInfo['ntitle'] : '文章';
                $detail['seo_title'] = $this->set_arcseotitle($detail['title'], $detail['seo_title']); // seo标题
                $detail['litpic'] = $this->get_default_pic($detail['litpic']); // 默认封面图
                $detail['add_time'] = $this->time_format($detail['add_time']);
                $detail['content'] = '';

                unset($detail['users_free']);
                unset($detail['downcount']);
                /*产品参数*/
                if (!empty($detail['attrlist_id'])) { // 新版参数
                    $productAttrModel = new \app\home\model\ProductAttr;
                    $attr_list = $productAttrModel->getProAttrNew($aid, 'a.attr_id,a.attr_name,b.attr_value,b.aid');
                } else { // 旧版参数
                    $productAttrModel = new \app\home\model\ProductAttr;
                    $attr_list = $productAttrModel->getProAttr($aid);
                }
                $attr_list = !empty($attr_list[$aid]) ? $attr_list[$aid] : [];
                foreach ($attr_list as $key => $val) {
                    $val['attr_value'] = htmlspecialchars_decode($val['attr_value']);
                    unset($val['aid']);
                    $attr_list[$key] = $val;
                }
                $detail['attr_list'] = !empty($attr_list) ? $attr_list : false;   //产品默认参数

                /*规格数据*/
                $api = new \app\api\model\v1\Api;
                $detail['spec_attr'] = $api->getSpecAttr($aid, $users);
                /* END */

                // 产品相册
                $productImgModel = new \app\home\model\ProductImg;
                $image_list = $productImgModel->getProImg($aid, 'aid,image_url,intro');
                $image_list = !empty($image_list[$aid]) ? $image_list[$aid] : [];
                foreach ($image_list as $key => $val) {
                    $val['image_url'] = $this->get_default_pic($val['image_url']);
                    isset($val['intro']) && $val['intro'] = htmlspecialchars_decode($val['intro']);
                    $image_list[$key] = $val;
                }
                $detail['image_list'] = !empty($image_list) ? $image_list : false;

                /*可控制的主表字段列表*/
                $detail['ifcontrolRow'] = Db::name('channelfield')->field('id,name')->where([
                    'channel_id' => $detail['channel'],
                    'ifmain' => 1,
                    'ifeditable' => 1,
                    'ifcontrol' => 0,
                    'status' => 1,
                ])->getAllWithIndex('name');

                // 设置默认原价
                $detail['old_price'] = $detail['users_price'];
                $detail['product_num'] = 1;
                $detail['spec_value_id'] = '';

                $detail['cart_total_num'] = 0;
                if (!empty($users['users_id'])) {
                    //购物车数量
                    $detail['cart_total_num'] = Db::name('shop_cart')->where(['users_id' => $users['users_id']])->sum('product_num');
                }

                // 获取自定义字段的数据
                $customField = [];
                $addtableName = $channeltypeInfo['table'] . '_content';
                $detailRow = Db::name($addtableName)->field('id,aid,add_time,update_time', true)->where('aid', $aid)->find();
                if (!empty($detailRow)) {
                    $fieldLogic = new \app\home\logic\FieldLogic();
                    $detailExt = $fieldLogic->getChannelFieldList($detailRow, $detail['channel']); // 自定义字段的数据格式处理
                    if (empty($channeltypeInfo['ifsystem'])) { // 自定义模型
                        // 如果存在自定义字段content，默认作为文档的正文内容。
                        // 如果不存在，将获取第一个html类型的内容，作为文档的正文内容。
                        if (!isset($detailExt['content'])) {
                            $contentField = Db::name('channelfield')->where([
                                'channel_id' => $detail['channel'],
                                'dtype' => 'htmltext',
                            ])->getField('name');
                            $detailExt['content'] = !empty($detailExt[$contentField]) ? $detailExt[$contentField] : '';
                        }
                    }
                    $detail['content'] = $detailExt['content'];
                    unset($detailExt['content']);

                    // 手机端详情内容
                    if (isset($detailExt['content_ey_m'])) {
                        $detail['content'] = $detailExt['content_ey_m'];
                        unset($detailExt['content_ey_m']);
                    }

                    if (!empty($detailExt)) {
                        $field = 'name, title, dtype';
                        $customField = Db::name('channelfield')->field($field)->where([
                            'name' => ['IN', array_keys($detailExt)],
                            'channel_id' => $detail['channel'],
                            'ifeditable' => 1
                        ])->getAllWithIndex('name');
                        if (!empty($customField)) {
                            foreach ($customField as $key => $value) {
                                if ('img' == $value['dtype']) {
                                    $customField[$key]['value'] = $this->get_default_pic($detailExt[$key]);
                                } else if ('media' == $value['dtype']) {
                                    $customField[$key]['value'] = $this->get_default_pic($detailExt[$key]);
                                } else if ('imgs' == $value['dtype']) {
                                    foreach ($detailExt[$key] as $kk => $vv) {
                                        $detailExt[$key][$kk]['image_url'] = $this->get_default_pic($vv['image_url']);
                                    }
                                    $customField[$key]['value'] = $detailExt[$key];
                                } else {
                                    $customField[$key]['value'] = $detailExt[$key];
                                }
                            }
                        }
                    }
                    $customField = array_values($customField);
                }
                $detail['customField'] = !empty($customField) ? $customField : false;

            }
            if (!empty($detail)) {
                if (0 <= $detail['arcrank']) { // 待审核稿件
                    $detail['title'] = htmlspecialchars_decode($detail['title']);
                    $detail['content'] = $this->html_httpimgurl($detail['content'], true); // 转换内容图片为http路径
                } else {
                    $detail = [
                        'arcrank' => $detail['arcrank'],
                    ];
                }
            }
            $detail = !empty($detail) ? $detail : false;
        }
        if (!empty($detail)){
            // 浏览量
            Db::name('archives')->where(['aid' => $aid])->setInc('click');
            $detail['click'] += 1;
        }
        return $detail;
    }
}